package my.shadowsocks.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 向被代理的客户端发送消息
 * @author fengbo
 * @date 2018/10/5
 */
public class ClientProxyHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(ClientProxyHandler.class);

    private ByteBuf clientCache;
    private InternetDataHandler internetDataHandler;
    private ChannelHandlerContext ctx;

    ClientProxyHandler(ByteBuf clientCache) {
        this.clientCache = clientCache;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (internetDataHandler != null) {
            internetDataHandler.sendMsg(msg);
        } else {
            ByteBuf buff = (ByteBuf) msg;
            clientCache.writeBytes(buff);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("ClientProxyHandler channelInactive close");
        channelClose();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("ClientProxyHandler error", cause);
        channelClose();
    }

    void sendMsg(Object msg) {
        ctx.writeAndFlush(msg);
    }

    void setInternetDataHandler(InternetDataHandler internetDataHandler) {
        this.internetDataHandler = internetDataHandler;
    }

    void channelClose() {
        ctx.close();
        if (clientCache != null) {
            clientCache.clear();
            clientCache = null;
        }
    }
}
